package controllers

import (
	"errors"
	"fmt"
	"gopkg.in/mgo.v2"
	"strconv"
	"steam_api/models"
	"encoding/json"
)

type SteamCollection struct {
	CollectionCout int   //记录集合的长度
	CollectionRecord interface{}  //记录的数据
	PageCount int  //分页数量
	PageEntrycount int //分页中记录条目数
}

func (steamobj *SteamCollection) Init (host string,database_name string,collection_name ...string) error {
	/*
	初始化函数，结构体实例后立刻调用此函数

	*/
	var steam_collections,_=steamobj.extract_collections(host,database_name,collection_name...)
	var merge_collections []interface{}
	//var index=0
	for collection_count,one_collection:=range steam_collections{

		steam_v,ok:=one_collection.([]map[string]interface {})
		if(!ok){
			s:=fmt.Sprintf("第%d记录集合,数据类型错误",collection_count)
			var err=errors.New(s)
			co_log.Warning(err.Error())
			steamobj.CollectionCout=0
			steamobj.CollectionRecord=[]map[string][]string{}
			return err
		}
		for _,one_row:=range steam_v {
			merge_collections=append(merge_collections, one_row)
		}
	}

	steamobj.CollectionRecord=merge_collections
	steamobj.CollectionCout=len(merge_collections)

	page_cout:=steamobj.CollectionCout/steamobj.PageEntrycount
	if steamobj.CollectionCout%steamobj.PageEntrycount>0{
		page_cout++
	}
	steamobj.PageCount=page_cout

	return nil
}

func (steamobj *SteamCollection) extract_collections(host string,database_name string,collection_name ...string) ([]interface{},error) {
	/*
	获取各个集合的数据记录
	@host: 主机名字
	@database_name:数据库名字
	@collection_name:集合名字
	*/
	database_url:=host+"/"+database_name
	session,err:=mgo.Dial(database_url)
	defer session.Close()
	if err != nil {
		s:=fmt.Sprintf("数据库连接错误 %s",err)
		co_log.Warning(s)
		var err=errors.New(s)
		return []interface{}{},err
	}

	var result_list []interface{}

	for _,one_collection_name:=range collection_name{
		var result []map[string]interface{}
		coll_obj:=session.DB(database_name).C(one_collection_name)
		err=coll_obj.Find(nil).All(&result)
		if err != nil {
			s:=fmt.Sprintf("%s 获取记录错误 %s",one_collection_name,err)
			co_log.Warning(s)
			var err=errors.New(s)
			return []interface{}{},err
		}
		result_list=append(result_list, result)
	}
	return result_list,nil
}


func (steamobj *SteamCollection) Get_page_collection(page int,controller *SteamController) (models.SteamPages,error) {
	/*
	获取分页数据
	@page: 页面序号
	@controller:
	*/
	var pagedata models.SteamPages
	if (page>steamobj.PageCount){
		page=steamobj.PageCount
	}
	start:=(page-1)*steamobj.PageEntrycount
	end:=page*steamobj.PageEntrycount
	if end>steamobj.CollectionCout{
		end=steamobj.CollectionCout
	}

	data,ok:=steamobj.CollectionRecord.([]interface{})
	if !ok{
		s:=fmt.Sprintf("数据格式错误 %s",data)
		co_log.Warning(s)
		return pagedata,errors.New(s)
	}

	page_result:=data[start:end]
	if page>1{
		pagedata.Previous=controller.Ctx.Input.Site()+":"+strconv.Itoa(controller.Ctx.Input.Port())+controller.Ctx.Input.URL()+"?page="+strconv.Itoa(page-1)

	}else {
		pagedata.Previous=nil
	}

	if page<steamobj.PageCount{
		pagedata.Next=controller.Ctx.Input.Site()+":"+strconv.Itoa(controller.Ctx.Input.Port())+controller.Ctx.Input.URL()+"?page="+strconv.Itoa(page+1)

	}else {
		pagedata.Next=nil
	}
	pagedata.Current=page
	var new_page_result []interface{}

	for _,row:=range page_result{
		var steam_infos models.SteamInfos
		row,ok:=row.(map[string]interface{})
		if !ok{
			continue
		}

		row["id"]=row["_id"]
		delete(row,"_id")  //删除键值对
		steam_data,_:=json.MarshalIndent(row,"","") //encode json

		err:=json.Unmarshal(steam_data,&steam_infos)  //decode json to struct
		if err==nil{
			var classimg =[]string{}
			for _,img:=range steam_infos.ClassImg{
				if img!=""{
					//img=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+"/medias/"+img
					img="/medias/"+img
				}
				classimg=append(classimg,img)
			}
			steam_infos.ClassImg=classimg

			var extendedpicture =[]string{}
			for _,img:=range steam_infos.ExtendedPicture{
				if img!=""{
					//img=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+"/medias/"+img
					img="/medias/"+img
				}
				extendedpicture=append(extendedpicture,img)
			}
			steam_infos.ExtendedPicture=extendedpicture

			var achievementspicture=[]string{}
			for _,img:=range steam_infos.AchievementsPicture{
				if img!=""{
					//img=this.Ctx.Input.Site()+":"+strconv.Itoa(this.Ctx.Input.Port())+"/medias/"+img
					img="/medias/"+img
				}
				achievementspicture=append(achievementspicture,img)
			}
			steam_infos.AchievementsPicture=achievementspicture


			new_page_result=append(new_page_result,steam_infos)
		}

	}

	pagedata.Count=steamobj.CollectionCout
	pagedata.PageCout=steamobj.PageCount
	pagedata.Results=new_page_result

	return pagedata,nil
}
